﻿using ECommerce.ProductService.Data;
using ECommerce.ProductService.Entities;
using ECommerce.Shared.Models;
using Microsoft.EntityFrameworkCore;
using ProductService.Entities;
using Shared;


namespace ECommerce.ProductService.Services;

public class ProductService : IProductService
{
    private readonly ProductDbContext _dbContext;

    public ProductService(ProductDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    /// <summary>
    /// 获取所有产品（含类别名称）
    /// </summary>
    public async Task<List<ProductDto>> GetAllProductsAsync()
    {
        return await _dbContext.Products
            .Include(p => p.Category) // 关联查询类别（避免延迟加载）
            .Select(p => new ProductDto
            {
                Id = p.Id,
                Name = p.Name,
                Description = p.Description,
                Price = p.Price,
                StockQuantity = p.StockQuantity,
                CategoryId = p.CategoryId,
                CategoryName = p.Category.Name // 传递类别名称到前端
            })
            .ToListAsync();
    }

    /// <summary>
    /// 根据 ID 获取产品
    /// </summary>
    public async Task<ProductDto> GetProductByIdAsync(Guid id)
    {
        var productDto = await _dbContext.Products
            .Include(p => p.Category)
            .Where(p => p.Id == id)
            .Select(p => new ProductDto
            {
                Id = p.Id,
                Name = p.Name,
                Description = p.Description,
                Price = p.Price,
                StockQuantity = p.StockQuantity,
                CategoryId = p.CategoryId,
                CategoryName = p.Category.Name
            })
            .FirstOrDefaultAsync();

        if (productDto == null)
        {
            throw new NotFoundException("产品", id);
        }

        return productDto;
    }

    /// <summary>
    /// 创建产品（需验证类别存在性和业务规则）
    /// </summary>
    public async Task<ProductDto> CreateProductAsync(CreateProductRequest request)
    {
        // 1. 验证类别是否存在
        var categoryExists = await _dbContext.Categories.AnyAsync(c => c.Id == request.CategoryId);
        if (!categoryExists)
        {
            throw new NotFoundException("类别", request.CategoryId);
        }

        // 2. 验证业务规则（价格、库存不能为负）
        if (request.Price < 0)
        {
            throw new BusinessException("产品价格不能为负数");
        }
        if (request.StockQuantity < 0)
        {
            throw new BusinessException("库存数量不能为负数");
        }

        // 3. 创建产品实体
        var product = new Product
        {
            Name = request.Name,
            Description = request.Description,
            Price = request.Price,
            StockQuantity = request.StockQuantity,
            CategoryId = request.CategoryId
        };

        // 4. 保存到数据库
        _dbContext.Products.Add(product);
        await _dbContext.SaveChangesAsync();

        // 5. 返回创建的产品（含类别名称）
        return await GetProductByIdAsync(product.Id);
    }

    /// <summary>
    /// 更新产品（支持部分字段更新）
    /// </summary>
    public async Task UpdateProductAsync(Guid id, UpdateProductRequest request)
    {
        // 1. 查找产品
        var product = await _dbContext.Products.FindAsync(id)
            ?? throw new NotFoundException("产品", id);

        // 2. 验证类别（如果更新了类别）
        if (request.CategoryId.HasValue)
        {
            var categoryExists = await _dbContext.Categories.AnyAsync(c => c.Id == request.CategoryId.Value);
            if (!categoryExists)
            {
                throw new NotFoundException("类别", request.CategoryId.Value);
            }
            product.CategoryId = request.CategoryId.Value;
        }

        // 3. 更新字段（仅更新非空字段）
        if (!string.IsNullOrEmpty(request.Name))
            product.Name = request.Name;

        if (!string.IsNullOrEmpty(request.Description))
            product.Description = request.Description;

        if (request.Price.HasValue && request.Price >= 0)
            product.Price = request.Price.Value;

        if (request.StockQuantity.HasValue && request.StockQuantity >= 0)
            product.StockQuantity = request.StockQuantity.Value;

        // 4. 保存更改（UpdatedAt 自动更新，见 ProductDbContext.SaveChangesAsync）
        await _dbContext.SaveChangesAsync();
    }

    /// <summary>
    /// 删除产品
    /// </summary>
    public async Task DeleteProductAsync(Guid id)
    {
        var product = await _dbContext.Products.FindAsync(id)
            ?? throw new NotFoundException("产品", id);

        _dbContext.Products.Remove(product);
        await _dbContext.SaveChangesAsync();
    }

    /// <summary>
    /// 获取所有类别
    /// </summary>
    public async Task<List<CategoryDto>> GetAllCategoriesAsync()
    {
        return await _dbContext.Categories
            .Select(c => new CategoryDto
            {
                Id = c.Id,
                Name = c.Name
            })
            .ToListAsync();
    }
}